// pages/booking/history.js
const api = require('../../utils/api');
const utils = require('../../utils/index');

Page({
  data: {
    bookingList: [],
    loading: false,
    showStatusDropdown: false,
    showOrderDropdown: false,
    page: 1,
    pageSize: 10,
    hasMore: true,
    selectedStatus: null,
    selectedOrderType: null,
    statusText: '订单状态',
    orderText: '订单类型'
  },

  onLoad: function () {
    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    // 加载历史订单列表
    this.loadBookingList();
  },

  onShow: function () {
    // 检查登录状态是否发生变化
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
  },

  // 返回上一页
  onTapBack: function () {
    wx.navigateBack();
  },

  // 切换状态下拉菜单
  toggleStatusDropdown: function () {
    this.setData({
      showStatusDropdown: !this.data.showStatusDropdown,
      showOrderDropdown: false // 关闭另一个下拉菜单
    });
  },

  // 切换订单类型下拉菜单
  toggleOrderDropdown: function () {
    this.setData({
      showOrderDropdown: !this.data.showOrderDropdown,
      showStatusDropdown: false // 关闭另一个下拉菜单
    });
  },

  // 选择订单状态
  selectStatus: function (e) {
    const status = e.currentTarget.dataset.status;
    let statusText = '全部';
    
    switch (status) {
      case '3':
        statusText = '已完成';
        break;
      case '4':
        statusText = '已取消';
        break;
      case 'all':
        statusText = '全部';
        break;
    }
    
    this.setData({
      selectedStatus: status === 'all' ? null : status,
      statusText: statusText,
      showStatusDropdown: false
    });
    
    this.resetAndLoadBookingList();
  },

  // 选择订单类型
  selectOrder: function (e) {
    const type = e.currentTarget.dataset.type;
    let orderText = '全部订单';
    
    switch (type) {
      case '0':
        orderText = '棋牌订单';
        break;
      case '1':
        orderText = '台球订单';
        break;
      case 'all':
        orderText = '全部订单';
        break;
    }
    
    this.setData({
      selectedOrderType: type === 'all' ? null : type,
      orderText: orderText,
      showOrderDropdown: false
    });
    
    this.resetAndLoadBookingList();
  },

  // 重置并加载订单列表
  resetAndLoadBookingList: function () {
    this.setData({
      page: 1,
      bookingList: [],
      hasMore: true,
      loading: false
    }, () => {
      this.loadBookingList();
    });
  },

  // 加载订单列表
  loadBookingList: function () {
    if (!this.data.hasMore) return;
    this.setData({ loading: true });
    
    // 构建请求参数
    const params = {
      page: this.data.page,
      page_size: this.data.pageSize
    };

    // 处理订单状态参数
    if (this.data.selectedStatus) {
      // 如果选择了特定状态，则只显示该状态的订单
      params.status = [parseInt(this.data.selectedStatus)];
    }
    
    // 处理订单类型参数
    if (this.data.selectedOrderType) {
      params.venue_type = this.data.selectedOrderType;
    }

    // 调用API获取订单列表
    api.order.getMyBookings(params)
      .then(res => {
        if (res.success) {
          const newList = res.data.list || [];
          const formattedList = newList.map(item => {
            // 格式化时间和日期
            const startTime = item.start_time ? new Date(item.start_time * 1000) : null;
            const endTime = item.end_time ? new Date(item.end_time * 1000) : null;
            
            let date = '';
            let time = '';
            
            if (startTime) {
              date = utils.formatDate(startTime);
              time = `${utils.formatTime(startTime)} - ${endTime ? utils.formatTime(endTime) : ''}`;
            }
            
            return {
              ...item,
              id: item.id,
              date: date,
              time: time,
              status: item.status,
              total_amount: item.total_amount || 0,
              createTime: utils.formatTimestampWithTime(item.created_at || item.create_time)
            };
          });

          // 更新数据
          this.setData({
            bookingList: this.data.page === 1 ? formattedList : [...this.data.bookingList, ...formattedList],
            page: this.data.page + 1,
            hasMore: newList.length >= this.data.pageSize,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.message || '获取订单列表失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      })
      .catch(err => {
        console.error('获取订单列表失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },

  // 查看订单详情
  onTapBookingDetail: function (e) {
    const bookingId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/booking/detail?id=${bookingId}`
    });
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.resetAndLoadBookingList();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadBookingList();
    }
  }
});